const fs = require('fs')
const path = require('path')
const copyVue = require('./copyVue')
const alert = require('cli-alerts');

const PATH = {
  'bootstrap.yml': 'src/server/',
  'package.json': '',
  '.henhouserc': 'src/server/'
}

// 服务目录结构
module.exports = async function copyService (name) {
  const syncCopy = name => new Promise((resolve, reject) => {
    fs.cp(path.join(__dirname, '../../tpl/website'), `node-${name}`, { recursive: true }, err => {
      if (err) throw err;
      console.log('文件目录结构创建成功');
      copyVue(`node-${name}/src/web-content/module/test`)
      console.log('创建test页面成功');
      let index = 0
      for (const file in PATH) {
        if (Object.hasOwnProperty.call(PATH, file)) {
          const p = PATH[file];
          fs.readFile(path.join(__dirname, '../../tpl/websiteChange', file), 'utf-8', (err, data) => {
            if (err) throw err;
            let fileName = name
            if (file === '.henhouserc') {
              fileName = name.replaceAll('-website', '').replaceAll('-', '/')
            }
            data = data.replace(/website/g, fileName)
            fs.writeFile(`node-${name}/${p}${file}`, data, err => {
              if(err) throw err;
              index++
              console.log(`${file} 文件创建成功`);
              if (index === Object.keys(PATH).length) {
                resolve()
              }
            })
          })
        }
      }
    })
  })
  await syncCopy(name)
  alert({
    type: `success`,
    name: `创建成功`,
    msg: `
    
cd node-${name}
npm install || yarn
    `
  })
}
